package com.lianqi.emcpframework.design.support;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import com.lianqi.emcpframework.design.domain.Entity;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

/**
 * @program emcp-framework
 * @ClassName AbstractEntity
 * @description:抽象实体类
 * @author: sky
 * @create: 2019/06/08 19:42
 */
@Getter(AccessLevel.PUBLIC)
public abstract class AbstractEntity<T, ID> implements Entity<T, ID> {

    /**
     * 版本标记 乐观锁方式控制并发操作
     */
    @Setter(AccessLevel.PRIVATE)
    private long version;

    /**
     * 创建时间戳
     */
    @Setter(AccessLevel.PROTECTED)
    private Date createTime;

    /**
     * 最后更新时间戳
     */
    @Setter(AccessLevel.PROTECTED)
    private Date lastUpdateTime;

    /**
     * 创建化前的操作
     */
    public void prePersist() {
        this.setVersion(new Long(1));
        this.setCreateTime(new Date());
        this.setLastUpdateTime(new Date());
    }

    /**
     * 更新数据前操作
     */
    public void preUpdate() {
        this.setVersion(new AtomicLong(getVersion()).incrementAndGet());
        this.setLastUpdateTime(new Date());
    }

    /**
     * 获取创建时间时间戳
     * 
     * @return
     */
    public Long getCreateTimeAsMS() {
        return toMs(getCreateTime());
    }

    /**
     * 获取更新时间时间戳
     * 
     * @return
     */
    public Long getUpdateTimeAsMS() {
        return toMs(getLastUpdateTime());
    }

    /**
     * 生成时间戳
     * 
     * @param date
     * @return
     */
    protected Long toMs(Date date) {
        return date == null ? null : date.getTime();
    }
}
